/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.contorller.uct;

import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.passport.common.DesUtils;
import com.apache.passport.common.PassportHelper;
import com.apache.portal.common.restfull.RequestMapping;
import com.apache.portal.common.restfull.ResultFullAnntation;
import com.apache.portal.common.restfull.SupperAction;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.rpc.common.LoadRpcService;
import com.apache.tools.ConfigUtil;
import com.apache.tools.PostHttp;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;
import com.apache.uct.common.ToolsUtil;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * description:用户中心client对接
 *
 */
@SuppressWarnings("serial")
@ResultFullAnntation(name = "uctClientAction", urlPatterns = { "/res/client/*"})
public class UctClientAction extends SupperAction {
    protected Logger log = Logger.getLogger(this.getClass());

    protected void doInvoke(HttpServletRequest request, HttpServletResponse response,
                            String methodType) throws Exception {
        Method method = doInvoke(this.getClass(), request, response, methodType, "");
        if (null != method) {
            Object obj = method.invoke(this, request, response);
            if (!ToolsUtil.isEmpty(obj)) {
                JSONObject array = JSONObject.fromObject(obj);
                this.outputJson(array.toString(), response, request.getParameter("callback"));
            }
        } else {
            gotoErrorPage(request, response, "请求方式有误或请求地址未定义");
        }
    }
    /**
     * 用户登录
     */
    @RequestMapping(value = "login", method = "post")
    protected void login(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ResultMsg resultMsg = new ResultMsg("F", "登录失败");
        Map<String, String> params = this.getParameterMap(request);
        log.info("login params-->"+params);
        String service_login_url = ConfigUtil.getInstance().getLocalByKey("config.properties","service_login_url");
        log.info("service_login_url-->"+service_login_url);
        if(StrUtil.isNull(service_login_url)){
            this.gotoErrorPage(request,response,"服务端登录地址未设置！");
            return;
        }

        //验证码判断
        resultMsg = checkRandCode(request, params);
        if (null != resultMsg) {
            gotoErrorPage(request,response,resultMsg.getMsg());
            return;
        }

        //发送登录请求
        JSONObject objs = JSONObject.fromObject(params);
        //"Content-type", "application/json; charset=utf-8" 方式发送请求
        String reslutStr = PostHttp.postHttpEntityJson(service_login_url,objs.toString());
        if(!StrUtil.isNull(reslutStr)){
            JSONObject res_json = JSONObject.fromObject(reslutStr);
            String msg = String.valueOf(res_json.get("msg"));
            String flag = String.valueOf(res_json.get("flag"));
            if("T".equals(flag)){
                JSONObject loginUser_json = (JSONObject)res_json.get("loginUser");
                String userEname = String.valueOf(loginUser_json.get("userEname"));
                String tokenId = String.valueOf(loginUser_json.get("tokenId"));
                LoginUser loginUser = PBOSSOTools.getLoginUserFromUserCenter(userEname, tokenId);
                request.getSession().setAttribute("loginUser", loginUser);
            }

        }
        log.info("登录结果："+reslutStr);
        this.outputJson(reslutStr, response, "");
    }

    /**
     * description:  用户退出方法
     */
    @RequestMapping(value = "logout", method = "get")
    protected void logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ResultMsg msg = new ResultMsg("F", "退出失败");
        String tokenCookie = PassportHelper.getInstance().getCurrCookie(request);
        String value = PassportHelper.getInstance().getCurrCookie(request, "_uc.sso");
        String userEname = DesUtils.getInstance().decrypt(value);
        Map<String, String> param = this.getParameterMap(request);
        log.info("logout params-->"+param);
        Map<String, Object> params = new HashMap<String,Object>();
        params.putAll(param);
        if (null == params) {
            params = new HashMap();
        }
        params.put("tokenId", tokenCookie);
        params.put("userEname", userEname);
        String sysEname = ToolsUtil.getInstance().getValueByKey("sysEname");
        params.put("sysEname", sysEname);
        params.put("sysAccreditip", request.getRemoteAddr());
        ResultEntity entity = LoadRpcService.service()
                .doServiceClient("ssoService", "logout", params,
                        PortalPubFactory.getInstance().getRpcInfo("sso"));
        if (("true".equals(entity.getResult())) && !ToolsUtil.isEmpty(entity.getEntity())) {
            Map<String, Object> logMap = new HashMap<String, Object>();
            LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
            logMap.put("log_userEname", loginUser.getUserEname());

            clearLoginInfo(request, response);
            msg = new ResultMsg("T", "退出成功");
//
//            logMap.put("logOperationType", "logout");
//            logMap.put("logClassName", User.class.getName());
//            logMap.put("logIp", PortalPubFactory.getLocalIp());
//            LogClient.getInstance().execute(logMap);//添加日志
        }
        String reslutStr = JSONObject.fromObject(msg).toString();
        log.info("["+userEname+"]退出结果："+reslutStr);
        this.outputJson(reslutStr, response, "");
    }

    /**
     * description:  验证验证码
     */
    private ResultMsg checkRandCode(HttpServletRequest request, Map<String, String> params) {
        String if_randCode = StrUtil.doNull(ConfigUtil.getInstance().getLocalByKey("config.properties","if_randCode"), "T");
        if ("F".equals(if_randCode)) {
            return null;
        }
        ResultMsg msg = null;
        String session_randCode = String.valueOf(request.getSession().getAttribute("randCode"));
        if (ToolsUtil.isNull(session_randCode))
            return null;
        if ((StrUtil.isNull(params.get("rand")))) {
            msg = new ResultMsg("F", "验证码不能为空");
            return msg;
        }
        if (!params.get("rand").equals(session_randCode)) {
            msg = new ResultMsg("F", "验证码错误");
            return msg;
        }
        return msg;
    }
    private void clearLoginInfo(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        try {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = new Cookie(cookies[i].getName(), null);
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        ArrayList lst = new ArrayList();
        Enumeration enumer = request.getSession().getAttributeNames();
        while (enumer.hasMoreElements()) {
            lst.add(enumer.nextElement());
        }
        for (int i = 0; i < lst.size(); i++) {
            request.getSession().removeAttribute(lst.get(i).toString());
        }
    }


}
